<?php
#                                                                                 
# author: Cody Sorgenfrey                                       
# (c)2013 South Hill Calvary Chapel                                               
#                                                                                 
include_once("../mysql/database_info.php");
include_once("../mysql/common.php");
include_once("../common.php");
$meta_key= null;
$meta_desc= null;
print_html_head("Registration Manager" ,$meta_key,$meta_desc);
if (empty($_GET['id'])){
	printf("Lo Siento, the link that brought you here is probably broken.");
	return 0;
} else{
	$id = $_GET['id'];
}
?>
<style type="text/css">
	#loginBox{
		width: 200px;
		height: 140px;
		text-align: center;
		padding-top: 30px;
		margin-right: auto;
		margin-left: auto;
		border-radius: 5px;
		box-shadow: 1px 1px 4px black;
	}
	#loginError{
		color: red;
	}
	h2.page_title>img{
		width: 26%;
		float: left;
		margin-right: 10px;
	}
	div#headerBar{
		width: 100%;
		margin-bottom: 10px;
		position: relative;
	}
	div#floatRightHeader{
		right:0px;
		display: inline;
		position: absolute;
	}
	div#floatLeftHeader{
		display: inline;
	}
	#download,
	#allWhoOwe,
	#delete,
	#add{
		width: 150px;
	}
	span#cancelSearch{
		cursor: pointer;
		width: 10px;
		height: 10px;
		margin-left: -15px;
		display: none;
	}
	input#searchBar{
		width: 200px;
	}
	.console{
		color: #b0b0b0;
		margin-top: 5px;
		height: 20px;
		width: 100%;
	}
	#registrationCount, 
	#pendingCollected, 
	#grandTotalCollected{
		display: inline;
		margin-right: 5px;
	}
	td, th{
		padding:5px;
		word-wrap: break-word;
	}
	.dottedLines{
		border-top: 1px dotted black;
	}
	tr.markedForDelete{
		background-color: rgba(0,150,255,0.45);
	}
	.tableWell{
		width: 100%;
		height: 20px;
		margin-top: 10px;
		background-repeat: no-repeat;
		background-size: 1140px;
		background-position-x: -75px;
		background-image: url("../images/borderTop.png");
	}
	#bottomWell{
		background-image: url("../images/borderBottom.png");
		background-position-y: -90px;
	}
</style>
<?
print_java_head(null);
?>
<script type="text/javascript">
	$(document).ready(function(){
		loadRegistration();
	});
	function loadRegistration(){
		if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
			var ajax = new XMLHttpRequest();
		} else { // code for IE6, IE5
			var ajax = new ActiveXObject("Microsoft.XMLHTTP");
		}
		ajax.open("GET", "request.php?id="+"<?echo $id;?>"+"&time="+(new Date()), true);
		ajax.send();
		ajax.onreadystatechange=function(){
			if (ajax.readyState==4 && ajax.status==200){
				printTable(ajax.responseText);
				$(".console").text($(".console").data("initial"));
			} else if (ajax.readyState!=4 && ajax.status==200){
				$(".console").text("Loading...");
			} else {
				$(".console").text("Error, could not load registration! Status="+ajax.status+" and state="+ajax.readyState+" and Text="+ajax.responseText);
			}
		}
	}
	function printTable(response){
		var Rows = response.split("|row|");
		if (getCookie("registration_login") != null){
			$(".page_title").html("<img src='"+Rows.shift()+"' />"+Rows.shift()+" Registration");
		} else {
			Rows.shift();
			$(".page_title").html(Rows.shift()+" Registration");
		}
		var headerRow = Rows.shift().split("|cell|");
		var headerRowString = "<tr>";
		for (var x=6;x<headerRow.length;x+=2){
			headerRowString += "<th name='"+headerRow[x+1]+"'>"+ headerRow[x] +"</th>";
		}
		headerRowString += "</tr>";
		$("#mainTable").append(headerRowString);
		for (var x=0;x<Rows.length;x++){
			var cells = Rows[x].split("|cell|");
			var rowString = "<tr>";
			for (var y=4;y<cells.length;y++){
				rowString += "<td>"+stripslashes(cells[y])+"</td>";
			}
			rowString += "</tr>";
			$("#mainTable").append(rowString);
			$("#mainTable").find("tr:last").data("rowData", {tableID: cells[0], id: cells[1], paid: cells[2], scholarship: cells[3]});
		}
		initPage();
	}
	function initPage(){
		$(".console").data("initial", "<?echo ($_REQUEST['console']) ? $_REQUEST['console'] : "Double click any cell to edit it.";?>");
		$("tr:not(tr:first)").filter(":odd").addClass("row_even");
		$("tr:not(tr:first)").addClass("dottedLines");
		makeLinksAndBindDblClick();
		updateHeaderBarData();
	}
	function makeLinksAndBindDblClick(){
		$("td").each(function(){
			if ($(this).html().search(/^.+@.+\..+$/) >= 0){
				$(this).html("<a href='mailto:"+$(this).text()+"'>"+$(this).text()+"</a>");
			}
			$(this).bind("dblclick", function(event){
				editCell($(this));
			});
		});
	}
	function updateHeaderBarData(){
		$("#registrationCount").text(($("tr").length-1) + " Registrations");
		var total = 0;
		var pending = 0;
		$("tr:not(tr:first)").find("td:last").each(function(index){
			if ($(this).parent().data("rowData").paid == "1"){
				total += parseFloat($(this).text());
			} else {
				pending += parseFloat($(this).text());
			}
		});
		$("#grandTotalCollected").text("$"+total.toFixed(2)+" Collected");
		$("#pendingCollected").text("$"+pending.toFixed(2)+" Pending");
	}
	function scaleLargeCells(){
		$("td").css("max-width", 100/($("tr").children().length));
	}
	function searchTable(val){
		if (val == ""){
			$("tr").css("display", "table-row");
			$("td").css("opacity", 1);
			$("#cancelSearch").css("display", "none");
			$("#searchBar").val("");
		} else {
			$("#cancelSearch").css("display", "inline");
			$("tr:not(tr:first)").css("display", "none");
			$("td").css("opacity", .5);
			$("td").each(function(){
				var regEx = new RegExp(val, "i");
				if ($(this).text().search(regEx) >= 0){
					$(this).css("display", "table-cell");
					$(this).css("opacity", 1);
					$(this).parent().css("display", "table-row");
				}
			});
		}
	}
	function showAllWhoOwe(button){
		if (button.innerHTML == "Show All Who Owe"){
			button.innerHTML = "Clear";
			$("tr:not(tr:first)").css("display", "none");
			$("tr:not(tr:first)").each(function(){
				if ($(this).data("rowData").paid == "0"){
					$(this).css("display", "table-row");
				}
			});
		} else {
			button.innerHTML = "Show All Who Owe";
			$("tr").css("display", "table-row");
		}
	}
	function makeSpreadsheet(id){
		window.location = "https://script.google.com/a/macros/southhillcalvary.org/s/AKfycbyVXzlSJxWxU0edHKMa3IZTQv1kUSBCX1ZweeIQ50rYsOcru0yO/exec?id="+id;
	}
	function toggleDelete(){
		if (!$("#delete").data("deleteMode")){
			$("#delete").data("deleteMode", true);
			$("#delete").text("Cancel");
			$(".console").text("Select the rows you want to delete, then click \"Delete Selected\".");
			$("tr:not(tr:first)").bind("click", function(event){
				markRowForDeletion(event.target);
			});
		} else {
			$("#delete").removeData("deleteMode");
			$("#delete").text("Delete a Row");
			$("#delete").unbind();
			$("#delete").bind("click", function(){
				toggleDelete();
			});
			$(".console").text($(".console").data("initial"));
			$("td").removeClass("markedForDelete");
			$("tr:not(tr:first)").unbind("click");
		}
	}
	function markRowForDeletion(tar){
		tar = $(tar).parent("tr");
		if ($(tar).data("delete")){
			$(tar).removeData("delete");
			$(tar).removeClass("markedForDelete");
		} else {
			$(tar).data("delete", true);
			$(tar).addClass("markedForDelete");
		}
		if ($("tr.markedForDelete").length != 0){
			$("#delete").text("Delete Selected");
			$("#delete").removeAttr("onclick");
			$("#delete").unbind();
			$("#delete").bind("click", function(){
				deleteSelectedRows();
			});
		} else {
			$("#delete").text("Cancel");
			$("#delete").unbind();
			$("#delete").bind("click", function(){
				toggleDelete();
			});
		}
	}
	function deleteSelectedRows(){
		if (confirm("Delete selected rows?")){
			var deleteString = null;
			$("tr.markedForDelete").each(function(){
				if (deleteString == null){
					deleteString = $(this).data("rowData").tableID+"|cell|"+$(this).data("rowData").id;
				} else {
					deleteString += "|row|"+$(this).data("rowData").tableID+"|cell|"+$(this).data("rowData").id;
				} 
			});
			if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
				var obj = new XMLHttpRequest();
			} else { // code for IE6, IE5
				var obj = new ActiveXObject("Microsoft.XMLHTTP");
			}
			obj.open("GET", "deleteRow.php?vars="+deleteString+"&time="+(new Date()), true);
			obj.send();
			$(".console").text("deleting...");
			obj.onreadystatechange=function(){
				if (obj.readyState==4 && obj.status==200){
					$(".console").text(obj.responseText);
					if (obj.responseText.search("Deleted") >= 0){
						$("tr.markedForDelete").remove();
						toggleDelete();
						updateHeaderBarData();
					}
				}
			}
		}
	}
	function editCell(cell){
		$("td").unbind("dblclick");
		var oldVal = $(cell).text();
		if (oldVal.length > 50){
			$(cell).html("<textarea></textarea>");
		} else {
			$(cell).html("<input type='text' />");
		}
		$(cell).children(":first").val(oldVal);
		$(cell).children(":first").data("oldVal", oldVal);
		$(cell).children(":first").bind("blur", function(event){
			endEditCell(event.target);
		});
		$(cell).children(":first").focus();
	}
	function endEditCell(box){
		var cell = $(box).parent();
		var row = $(cell).parent();
		var colNum = $(cell).siblings().length;
		$(box).unbind("blur");
		var newVal = $(box).val();
		if (newVal != $(box).data("oldVal")){
			ajaxUpdateCell(box, cell, row)
			if ( ($(cell).index() == colNum) || ($(cell).index() == colNum-1) ){
				if (prompt("Does this person still owe money?\nType yes or no.") == "no"){
					ajaxUpdatePaid("1", row);
				} else {
					ajaxUpdatePaid("0", row);
				}
			}
		} else {
			$(cell).text(newVal);
			makeLinksAndBindDblClick();
		}
	}
	function ajaxUpdateCell(box, cell, row){
		var tableID = $(row).data("rowData").tableID;
		var id = $(row).data("rowData").id;
		var column = $("th:eq("+$(cell).index()+")").attr("name");
		if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
			var obj = new XMLHttpRequest();
		} else { // code for IE6, IE5
			var obj = new ActiveXObject("Microsoft.XMLHTTP");
		}
		var vars = id+"|cell|"+tableID+"|cell|"+column+"|cell|"+$(box).val();
		obj.open("GET", "updateRow.php?vars="+vars+"&time="+(new Date()), true);
		obj.send();
		$(".console").text("sending...");
		obj.onreadystatechange=function(){
			if (obj.readyState==4 && obj.status==200){
				$(".console").text(obj.responseText);
				if (obj.responseText.search("Updated") >= 0){
					var col = obj.responseText.split(":")[1];
					$(".console").text("Updated Column: \""+$("th[name="+col+"]").text()+"\"");
					$(cell).text($(box).val());
					makeLinksAndBindDblClick();
				} else {
					$(cell).text($(cell).find("input").data("oldVal"));
					makeLinksAndBindDblClick();
				}
			}
		}
	}
	function ajaxUpdatePaid(val, row){
		var tableID = $(row).data("rowData").tableID;
		var id = $(row).data("rowData").id;
		if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
			var obj = new XMLHttpRequest();
		} else { // code for IE6, IE5
			var obj = new ActiveXObject("Microsoft.XMLHTTP");
		}
		var vars = id+"|cell|"+tableID+"|cell|Paid|cell|"+val;
		obj.open("GET", "updateRow.php?vars="+vars+"&time="+(new Date()), true);
		obj.send();
		$(".console").text("sending...");
		obj.onreadystatechange=function(){
			if (obj.readyState==4 && obj.status==200){
				$(".console").text(obj.responseText);
				if (obj.responseText.search("Updated") >= 0){
					$(row).data("rowData").paid = val;
					setTimeout(function(){
						updateHeaderBarData();
					}, 500);
				} else {
					$(".console").text("Error, could not update value.");
					return 0;
				}
			}
		}
	}
	function stripslashes(str) {
		str=str.replace(/\\'/g,'\'');
		str=str.replace(/\\"/g,'"');
		str=str.replace(/\\0/g,'\0');
		str=str.replace(/\\\\/g,'\\');
		return str;
	}
	function checkTables(){
		if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
			var obj = new XMLHttpRequest();
		} else { // code for IE6, IE5
			var obj = new ActiveXObject("Microsoft.XMLHTTP");
		}
		obj.open("GET", "checkTables.php?tableID="+"<?echo $id;?>"+"&time="+(new Date()), true);
		obj.send();
		$(".console").text("Working...");
		obj.onreadystatechange=function(){
			if (obj.readyState==4 && obj.status==200){
				if (obj.responseText.search("Single Table") >= 0){
					addNewRow("<?echo $id;?>");
				} else {
					$(".console").html(obj.responseText);
				}
			}
		}
	}
	function addNewRow(tableID){
		$("tr:last").prev().clone(true).appendTo("#mainTable");
		$("tr:last").data("rowData").tableID = tableID;
		$("tr:last>td").text("");
		$("tr:last>td:last").text("0");
		ajaxAddRow($("tr:last"));
		editCell($("tr:last>td:first"));
	}
	function ajaxAddRow(row){
		var tableID = $(row).data("rowData").tableID;
		if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
			var obj = new XMLHttpRequest();
		} else { // code for IE6, IE5
			var obj = new ActiveXObject("Microsoft.XMLHTTP");
		}
		obj.open("GET", "addRow.php?tableID="+tableID+"&time="+(new Date()), true);
		obj.send();
		$(".console").text("Adding...");
		obj.onreadystatechange=function(){
			if (obj.readyState==4 && obj.status==200){
				$(".console").text("Please fill out row.");
				if (obj.responseText.search("Error") < 0){
					$("tr:last").data("rowData").id = obj.responseText;
					$("tr:last").data("rowData").paid = "0";
					$("tr:last").data("rowData").scholarship = "0";
					setTimeout(function(){
						updateHeaderBarData();
					}, 500);
				} else {
					$(".console").text("Error, could not create row.");
					return 0;
				}
			}
		}
	}
	function getCookie(c_name){
		var c_value = document.cookie;
		var c_start = c_value.indexOf(" " + c_name + "=");
		if (c_start == -1){
			c_start = c_value.indexOf(c_name + "=");
		}
		if (c_start == -1){
			c_value = null;
		}
		else{
			c_start = c_value.indexOf("=", c_start) + 1;
			var c_end = c_value.indexOf(";", c_start);
			if (c_end == -1){
				c_end = c_value.length;
			}
			c_value = unescape(c_value.substring(c_start,c_end));
		}
		return c_value;
	}
</script>
<?
begin_body();
page_title_no_content("Registration Manager");
if ($_POST['pass'] == "He1sR1sen"){
	?>
	<script type="text/javascript">
		document.cookie = "registration_login=1";
		document.location.search = "?id=<?echo $id;?>";
	</script>
	<?
} else if (!empty($_POST['pass'])){
	?>
	<script type="text/javascript">
		document.location.search = "?id=<?echo $id;?>&loginError=Incorrect+Password";
	</script>
	<?
}
if (empty($_COOKIE['registration_login'])){
	?>
	<div id='loginBox'>
	<form method="post">
	<h3>Password</h3><br>
	<input name='pass' type="password" id='loginPassword'><br><br>
	<button>Login</button><br>
	<p id="loginError"><?echo $_GET['loginError']?></p>
	</form>
	</div>
	<?
	end_page_title();
	end_body();
	return 0;
}
?>
<div id='headerBar'>
	<div id='floatLeftHeader'>
		<div id='registrationCount'>0 Registrations</div><br>
		<div id='grandTotalCollected'>$0 Collected</div><br>
		<div id='pendingCollected'>$0 Pending</div>
		<br><br>
		<button id='download' onclick="makeSpreadsheet('<?echo $id;?>')">Google Spreadsheet</button>
		<button id='allWhoOwe' onclick="showAllWhoOwe(this)">Show All Who Owe</button>
		<button id='delete' onclick="toggleDelete()">Delete a Row</button>
		<button id='add' onclick='checkTables()'>Add a Row</button>
	</div>
	<div id='floatRightHeader'>
		<span class='noPlaceholder'>Search: </span><input type="text" id='searchBar' placeholder="Search" onkeyup="searchTable(this.value)" /><span id='cancelSearch' onclick="searchTable('');">x</span>
	</div>
	<br><br>
	<div class='console'></div>
</div>
<div class='tableWell' id="topWell"></div>
<table id='mainTable'>
</table>
<div class="tableWell" id="bottomWell"></div>
<?
end_page_title();
end_body();
?>